package com.lahuan.rpc.protocol.netty.server;

import com.alibaba.fastjson.JSON;
import com.lahuan.rpc.protocol.tcp.CustomTcpMessage;
import com.lahuan.rpc.protocol.tcp.RpcfxRequest;
import com.lahuan.rpc.protocol.tcp.RpcfxResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ServerInboundHandler extends ChannelInboundHandlerAdapter {
  

    private HttpRequest request;
    ServerInvoker invoker;
    public ServerInboundHandler(ServerInvoker invoker) {
        this.invoker = invoker;
    }

    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        if (msg instanceof CustomTcpMessage) {
            CustomTcpMessage rec = (CustomTcpMessage) msg;
            String body = rec.getBody();
            String header = rec.getHeader();
            System.out.println("rec header:"+header);
            System.out.println("rec body:"+body);


            RpcfxRequest req = JSON.parseObject(body, RpcfxRequest.class);
            RpcfxResponse rep = invoker.invoke(req);
            String res = JSON.toJSONString(rep);
            CustomTcpMessage response = new CustomTcpMessage();
            //服务端将header原路返回
            response.setHeader(header);
            response.setBody(res);
            ctx.write(response);
            ctx.flush();
        }  
    }  
  
    @Override  
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();  
    }  
  
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause.getMessage());  
        ctx.close();  
    }  
  
} 